package no.saiboten.tourbuilder.bracket.impl;

import no.saiboten.tourbuilder.bracket.Bracket;
import no.saiboten.tourbuilder.bracket.BracketDAO;
import no.saiboten.tourbuilder.bracket.BracketService;
import no.saiboten.tourbuilder.bracket.Match;
import no.saiboten.tourbuilder.bracket.Round;
import no.saiboten.tourbuilder.tournament.Tournament;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class BracketServiceImpl implements BracketService {

	@Autowired
	BracketDAO bracketDAO;

	@Override
	public Bracket createBracket(Tournament tournament) {
		Bracket bracket = new Bracket(tournament.getId(),
				tournament.getTournamentSize(), tournament.getUsers());
		bracketDAO.addBracket(bracket);
		return bracket;
	}

	@Override
	public void reportLoss(String bracketId, String userid, int pointsFor,
			int pointsAgainst) {

		Bracket bracket = bracketDAO.getBracket(bracketId);

		Round round = bracket.getRounds().get(bracket.getCurrentRound());

		boolean roundFinished = true;

		for (Match match : round.getMatches()) {

			if (match.getHome().getUserName().equals(userid)) {
				match.setFinished(true);
				match.setPointsHome(pointsFor);
				match.setPointsAway(pointsAgainst);
			} else if (match.getAway().getUserName().equals(userid)) {
				match.setFinished(true);
				match.setPointsAway(pointsFor);
				match.setPointsHome(pointsAgainst);
			}
			if (!match.isFinished()) {
				roundFinished = false;
			}
		}

		if (roundFinished) {
			bracket.setCurrentRound(bracket.getCurrentRound() + 1);
		}

		return;
	}

	@Override
	public boolean isUserStillPlaying(String userid, String bracketId) {
		Bracket bracket = bracketDAO.getBracket(bracketId);
		Round round = bracket.getRounds().get(bracket.getCurrentRound());

		for (Match match : round.getMatches()) {
			if (!match.isFinished()
					&& (match.getHome().getUserName().equals(userid) || match
							.getAway().getUserName().equals(userid))) {
				return true;
			}
		}
		return false;
	}
}
